package com.lebang.service.sys;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.lebang.component.RedisClient;
import com.lebang.entity.LbbDict;
import com.lebang.example.LbbDictExample;
import com.lebang.mapper.LbbDictMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: hwq
 * @Date: 2019/6/6 9:30
 * @Version 1.0
 */
@Service
public class DictService {
    @Autowired
    private LbbDictMapper lbbDictMapper;
    @Autowired
    private RedisClient redisClient;
    public static final String DICT_HASH = "DICT_HASH_CACHE";
    private static final String TASK_ID = "task_by_newhand";

    public LbbDict selectByKeyName(String keyName) {
        return this.selectByKeyNameInRedis(keyName);
    }

    public LbbDict selectByKeyNameInRedis(String keyName) {
        LbbDict dict;
        String str = redisClient.hget(DICT_HASH, keyName);
        if (str != null) {
            dict = JSON.parseObject(str, LbbDict.class);
        } else {
            dict = lbbDictMapper.selectByKeyName(keyName);
            if(dict!=null){
                redisClient.hset(DICT_HASH, keyName, JSON.toJSONString(dict));
            }
        }
        return dict;
    }

    public int insertSelective(LbbDict dict) {
        return lbbDictMapper.insertSelective(dict);
    }

    public int updateByPrimaryKeySelective(LbbDict dict) {
        redisClient.hdel(DICT_HASH,dict.getKeyname());
        if("fuzhi".equals(dict.getKeyname())){
            redisClient.del("XIANYU_YAOXIN_URL");
        }
        return lbbDictMapper.updateByPrimaryKeySelective(dict);
    }

    public LbbDict select(Long id) {
        return lbbDictMapper.selectByPrimaryKey(id);
    }

    public List<LbbDict> selectByExample(LbbDictExample example) {
        return lbbDictMapper.selectByExample(example);
    }

    public Long countByExample(LbbDictExample example) {
        return lbbDictMapper.countByExample(example);
    }

    public void delete(Integer id) {
        lbbDictMapper.deleteByPrimaryKey(id.longValue());
    }

    public int selectIntByKeyName(String name) {
        LbbDict dict = this.selectByKeyName(name);
        int i = Integer.parseInt(dict.getKeyvalue());
        return i;
    }
}
